package org.yasukusury.crawler.variation;

import org.apache.http.client.utils.DateUtils;
import org.apache.http.client.utils.URIBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.yasukusury.crawler.dao.Copy;
import org.yasukusury.crawler.helper.Utils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.CountDownLatch;

import static org.yasukusury.crawler.helper.Utils.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Y
 * Date: 2017-11-11
 * Time: 21:57
 */
public class AmazonUSCrawler extends AbstractBatches {

    private URI uri;
    private CountDownLatch cdl;

    public AmazonUSCrawler(String asin, ConcurrentLinkedDeque<Copy> list, int pages, int copyCount, CountDownLatch cdl) {
        this.asin = asin;
        this.list = list;
        this.pages = pages;
        this.copyCount = copyCount;
        this.cdl = cdl;
        pageNum = String.valueOf(pages);
    }

    public void start() throws InterruptedException {
        pageTraverse();
        exit(false);
    }

    private void skip() {
        skip(null);
    }

    private void skip(String msg) {
        if (msg != null)
            System.out.println(msg);
        else
            System.out.println(String.format("ASIN : %s 第 %d 页评论链接连接失败", asin, pages));
        copyCount -= 10;
    }

    private void exit(boolean except) throws InterruptedException {
        cdl.countDown();
        if (except) {
            System.out.println(String.format("ASIN : %s 评论链接连接失败", asin));
            throw new InterruptedException();
        }
        Thread.currentThread().interrupt();
    }

    void pageTraverse() throws InterruptedException {
        while (copyCount > 0) {
            pageNum = String.valueOf(pages);
            fillCopies();
            pages++;
        }
    }

    void fillCopies() throws InterruptedException {
        Document reviewDoc;
        try {
            urlPrase(asin);
            reviewDoc = httpClientGet(uri, asin, pages);
        } catch (URISyntaxException | IOException e) {
            skip();
            return;
        }
        if (reviewDoc == null) {
            skip();
            return;
        }
        Element e = reviewDoc.getElementById("cm_cr-review_list");
        if (e == null) {
            skip(String.format("ASIN : %s 第 %d 页评论链接没有评论", asin, pages));
            return;
        }
        Elements reviewList = e.children();

        for (int i = 1; i <= 10 && copyCount > 0; i++) {
            list.add(oneCopy(reviewList, i));
        }
    }

    private Copy oneCopy(Elements reviewList, int index) {

        Elements es;

        Element list = reviewList.get(index).child(0);
        Element star = null;
        es = Jsoup.parse(list.html()).select("span.a-icon-alt");
        if (es != null)
            if (es.first() != null)
                star = es.first();
        Element title = null;
        es = Jsoup.parse(list.html()).select("a[data-hook=review-title]");
        if (es != null)
            if (es.first() != null)
                title = es.first();
        Element reviewer = null;
        es = Jsoup.parse(list.html()).select("a[data-hook=review-author]");
        if (es != null)
            if (es.first() != null)
                reviewer = es.first();
        Element createDate = null;
        es = Jsoup.parse(list.html()).select("span[data-hook=review-date]");
        if (es != null)
            if (es.first() != null)
                createDate = es.first();
        Element purchased = null;
        es = Jsoup.parse(list.html()).select("span[data-hook=avp-badge]");
        if (es != null)
            if (es.first() != null)
                purchased = es.first();
        Element content = null;
        es = Jsoup.parse(list.html()).select("span[data-hook=review-body]");
        if (es != null)
            if (es.first() != null)
                content = es.first();

        Integer starInteger = Integer.valueOf(getPlainText(star).substring(0, 1));
        String titleText = getPlainText(title);
        String reviewerText = getPlainText(reviewer);
        Date date = DateUtils.parseDate(dateparse(Utils.getPlainText(createDate)), dateFormat);
        getPlainText(reviewer);
        String vp = getPlainText(purchased);
        String contentText = getPlainText(content);

        Copy copy = new Copy();
        copy.setAsin(asin);
        copy.setStar(starInteger);
        copy.setTitle(titleText);
        copy.setReviewer(reviewerText);
        copy.setCreateDate(date);
        copy.setPurchased(vp);
        copy.setContent(contentText);

        copyCount--;
        return copy;
    }

    private void urlPrase(String asin) throws URISyntaxException {
        uri = new URIBuilder()
                .setScheme("https")
                .setHost("www.amazon.com")
                .setPath("/product-reviews/" + asin)
                .setParameter(param[0], param[1])
                .setParameter(param[2], param[3])
                .setParameter(param[4], param[5])
                .setParameter(param[6], pageNum)
                .build();
    }

    String dateparse(String text) {
        String[] date = text.substring(3).split(" ");
        int m, i;
        for (i = 0; i < 12; i++) {
            if (month[i].equals(date[0])) {
                break;
            }
        }
        m = i + 1;
        return String.format("%s-%s-%s", date[2], String.valueOf(m), date[1].substring(0, date[1].length() - 1));
    }
}
